package com.maisonliberte.crawller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.maisonliberte.conf.Config;
import com.maisonliberte.dao.Dao;
import com.maisonliberte.entity.Staff;
import com.maisonliberte.util.FileUtil;
import com.maisonliberte.util.HttpUtil;
import com.maisonliberte.util.NetUtil;

abstract public class AbstractBrandCrawler {
	
	protected String url;
	protected String charset;
	protected List<String> parsingDataList;
	protected List<Staff> staffList;
	
	public AbstractBrandCrawler(){
		
	}
	
	public void process() throws Exception{
		
		try{
			// reset	
			parsingDataList = new ArrayList<String>();
			staffList = new ArrayList<Staff>();
			
			parsingData(url);
			for(String pData : parsingDataList){
				Staff staff = getBrandInfo(pData);
				staffList.add(staff);
			}
			downloadBrandImage();
			uploadBrandImage();
			updateBrandInfo();
			
			System.out.println(String.format("crawled count : %d", staffList.size()));
			
		}catch(Exception ex){
			throw ex;
		}
		
	}
	
	private String requestUrl(String _url) throws Exception {
		return HttpUtil.httpGet(_url, this.charset);
	}
	
	private void parsingData(String _url) throws Exception {
		String nextUrl = "";
		String parsingResult = requestUrl(_url);
		if(parsingResult.isEmpty()) return;
		
		analyzeParsedData(parsingResult);
		System.out.println("crawled at the URL : " + _url);
		if(!(nextUrl = getNextPage(parsingResult)).isEmpty()){
			parsingData(nextUrl);
		}
	}
	
	private void downloadBrandImage() throws Exception{
		for(Staff staff: staffList){
			String imgUrl = HttpUtil.saveImage(staff.getPic_src());
			staff.setPic_local(imgUrl);
		}
	}
	
	private void uploadBrandImage() throws Exception{
		//String uploadPath = Config.getInstance().ftpPathList.get(target);
		//Map<String, String> uploadTargets = new HashMap<String, String>();
		for(Staff staff : staffList){
			if(!staff.getPic_local().isEmpty()){
				staff.setPic_tar(String.format("%s/%s", Config.getInstance().brand_ftppath, FileUtil.getFilename(staff.getPic_src())));
				//uploadTargets.put(staff.getPic_local(), staff.getPic_tar());
				HttpUtil.upload("http://maisonimage1.comeze.com/upload_act.php", staff.getPic_local());
			}
		}
		
		//NetUtil.ftpUploadFile(uploadTargets, Config.getInstance().ftpUrl, Config.getInstance().ftpUserid, Config.getInstance().ftpPwd);
	}
	
	private void updateBrandInfo() throws Exception{
		Dao.getInstance().insertBrands(staffList);
	}
	
	public void setCharset(String charset) {
		this.charset = charset;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	protected String getCategoryId(){
		
		String categoryId = "";
		
		return categoryId;
	}
	
	abstract public String getNextPage(String data) throws Exception;
	abstract public void analyzeParsedData(String data) throws Exception;
	abstract public Staff getBrandInfo(String data) throws Exception;
	
}
